package logger

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"strings"
	"time"

	"github.com/opensearch-project/opensearch-go"
	"github.com/opensearch-project/opensearch-go/opensearchapi"
)

func NewOpensearch(ctx context.Context, addresses []string, indexName string) *Opensearch {
	client, err := opensearch.NewClient(opensearch.Config{
		Addresses: addresses,
	})
	if err != nil {
		fmt.Printf("Error creating the OpenSearch client: %v", err)
	}

	return &Opensearch{
		ctx:       ctx,
		client:    client,
		indexName: indexName,
	}
}

type Opensearch struct {
	ctx       context.Context
	client    *opensearch.Client
	indexName string
}

func (r *Opensearch) Log(message string) error {
	fmt.Println("Logging to OpenSearch:", message)

	doc := map[string]interface{}{
		"message":   message,
		"timestamp": time.Now().Format(time.RFC3339),
	}

	body, err := json.Marshal(doc)
	if err != nil {
		return fmt.Errorf("failed to marshal log document: %v", err)
	}

	req := opensearchapi.IndexRequest{
		Index: r.indexName,
		Body:  strings.NewReader(string(body)),
	}

	res, err := req.Do(r.ctx, r.client)
	if err != nil {
		return fmt.Errorf("failed to log to OpenSearch: %v", err)
	}
	defer func(Body io.ReadCloser) {
		err := Body.Close()
		if err != nil {
			panic(err)
		}
	}(res.Body)
	if res.IsError() {
		return fmt.Errorf("error indexing document to OpenSearch: %s", res.String())
	}

	return nil
}
